/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.SimpleError;
import org.xptracker.domain.Customer;
import org.xptracker.domain.Story;
import org.xptracker.persistence.PersistenceManager;

import java.util.List;

@UrlBinding("/Customers.action")
public class CustomersActionBean extends StandardActionBean {

  private List<Customer> customers;


  public List<Customer> getCustomers() {
    return customers;
  }

  public void setCustomers(List<Customer> customers) {
    this.customers = customers;
  }

  @DefaultHandler
  public Resolution listCustomers() {
    return new ForwardResolution("/admin/customers.jsp");
  }

  @HandlesEvent("Add")
  public Resolution addCustomer() {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        String customerName = param("name");
        Customer customer = domain.loadCustomer(customerName);
        if(customer == null) {
          receiver.insert(new Customer(customerName));
          getContext().getMessages().add(new SimpleMessage("Added customer ''{0}''",customerName));
        } else {
          getContext().getValidationErrors().add("name", alreadyExistsError("Customer", customerName));
        }
        return redirectBack();
      }
    });
  }

  private RedirectResolution redirectBack() {
    return new RedirectResolution(CustomersActionBean.class).flash(CustomersActionBean.this);
  }

  @HandlesEvent("Delete")
  public Resolution deleteCustomer() {
    return persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Resolution>() {
      public Resolution doUpdate(PersistenceManager.UpdateReceiver receiver) {
        String customerId = param("uuid");
        Customer customer = loadEntity(Customer.class, customerId);
        if(customer != null) {
          final String customerName = customer.getName();
          List<Story> stories = domain.listStoriesByCustomer(customer);
          for(Story story : stories) {
            story.getCustomers().remove(customer);
            receiver.update(story);
            getContext().getMessages().add(new SimpleMessage("Customer removed from story {0}", story.getExtId()));
          }
          receiver.remove(customer);
          getContext().getMessages().add(new SimpleMessage("Deleted customer {0}", customerName));
        } else {
          getContext().getValidationErrors().add("name", new SimpleError("Customer with id ''{1}'' does not exist", customerId));
        }
        return redirectBack();
      }
    });
  }

  @Before(stages=LifecycleStage.BindingAndValidation)
  public void provideCustomers() {
    this.customers = domain.listCustomers();
  }
}
